<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
class Common extends Controller
{
   public function _initialize(){
       parent::_initialize();
       
       if (!session('loginname','','admin')||!session('loginid','','admin')) {
           $controller=request()->controller();
           $action=request()->action();
           if ($controller=='Index' && $action='index') {
                $this->redirect('login/index');
           }
           $this->error('未登录，禁止访问','login/index');
       }
       $config=db('config')->find();
       $config=json_decode($config['config'],true);
       $this->assign('config',$config);
       $this->assign('admin',session('loginname','','admin'));
   } 
      /**
     * 栏目图片上传
     */
    public function uploadImg(){
        if (request()->isPost()) {
            $data=input('post.');
            $file = request()->file('imgfile');
            if ($file) {
                 $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    $pic= "uploads\\". $info->getSaveName();
                 }
            }
        }
        return json(['code'=>1,'msg'=>'上传成功','path'=>$pic]);
    }
    /**
     * 单张图片删除
     */
    public function delImg($url=""){
        $path=ROOT_PATH . "public\\" . $url;
        if ($url!==""||!empty($url)) {
            if  (file_exists($path)) {
                $res=unlink($path);
                if ($res) {
                    $this->delpic($url);
                    return json(['code'=>1,'msg'=>'删除成功']);
                }
                return json(['code'=>0,'msg'=>'删除失败']);
            }
            $this->delpic($url);
            return json(['code'=>2,'msg'=>'文件不存在']);
        }
        
    }
    // 删除图片表里的数据
    public function delpic($url){
        $pic=db('pic')->where('pic',$url)->field('id')->find();
        if ($pic) {
            db('pic')->delete($pic['id']);
        }
    }
}